﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CC98.Data;
using CC98.Network;
using CC98.Network.Primitives;

namespace CC98
{
    /// <summary>
    /// The top abstraction of CC98Client including CC98HttpClient and CC98HtmlParser
    /// </summary>
    public class CC98Client : NotifyPropertyChangedBase
    {
        public CC98Client(string username) : this(DefaultCC98HttpClientFactory.Instance.GetClient(username)) { }

        public CC98Client(CC98HttpClient httpClient)
        {
            if (httpClient == null)
                throw new ArgumentNullException("httpClient");
            // Init
            this.HttpClient = httpClient;
            this.HttpClient.AuthenticationStateChanged += HttpClientAuthenticationStateChanged;
        }
        
        /// <summary>
        /// Current user
        /// </summary>
        public User CurrentUser
        {
            get
            {
                return UserManager.Instance.GetUser(this.HttpClient.Username);
            }
        }

        #region IsLoggedIn

        private bool _IsLoggedIn;

        public bool IsLoggedIn
        {
            get
            {
                return this._IsLoggedIn;
            }
            set
            {
                if (this._IsLoggedIn != value)
                {
                    this._IsLoggedIn = value;
                    this.OnPropertyChanged("IsLoggedIn");
                }
            }
        }

        #endregion

        public Session GetSession()
        {
            return this.HttpClient.GetSession();
        }

        public event EventHandler AuthenticationStateChanged;

        protected CC98HttpClient HttpClient { get; private set; }

        protected virtual void HttpClientAuthenticationStateChanged(object sender, EventArgs e)
        {
            this.IsLoggedIn = this.HttpClient.IsAuthenticated;
            if (this.AuthenticationStateChanged != null)
                this.AuthenticationStateChanged(this, new EventArgs());
        }
    }
}
